package cn.tedu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Server {
	public static void main(String[] args) throws IOException {
		//开启服务器通道
		ServerSocketChannel ssc =ServerSocketChannel.open();
		//绑定端口
		ssc.bind(new InetSocketAddress(8070));
		//设置非阻塞
		ssc.configureBlocking(false);
		//开启选择器
		Selector selc=Selector.open();
		//将服务器注册到选择器上
		ssc.register(selc,SelectionKey.OP_ACCEPT );

		while (true) {
			// 选择，选择出已经注册的通道
			selc.select();
			// 获取这次选择出来的通道的事件
			Set<SelectionKey> keys = selc.selectedKeys();
			Iterator<SelectionKey> it = keys.iterator();
			while (it.hasNext()) {
				SelectionKey key = it.next();
				// 接收
				if (key.isAcceptable()) {
					// 获取通道
					ServerSocketChannel sscx = (ServerSocketChannel) key.channel();
					System.out.println("接到一个连接~~~~~");
					// 接收连接
					SocketChannel sc = sscx.accept();
					//设置非阻塞
					sc.configureBlocking(false);
					//注册读/写事件
					//后一次的注册事件会覆盖前一个注册事件
					sc.register(
							selc, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
				}
				//可读事件
				if(key.isReadable()){

					SocketChannel sc=(SocketChannel) key.channel();
					ByteBuffer buffer=ByteBuffer.allocate(1024);
					sc.read(buffer);
					System.out.println(
							new String(buffer.array(),0,buffer.position()));
					//移除到可读事件
					sc.register(selc, key.interestOps()^SelectionKey.OP_READ);
//					sc.register(selc, key.interestOps()-SelectionKey.OP_READ);

				}
				//可写事件
				if(key.isWritable()){
					SocketChannel sc=(SocketChannel) key.channel();
					sc.write(ByteBuffer.wrap("hello client~~".getBytes()));
					//移除可写事件
					sc.register(selc,key.interestOps()-SelectionKey.OP_WRITE);

				}
				it.remove();
			}
		}


	}
}
